import React from 'react';
import {inject, observer} from 'mobx-react';
import {Button, Modal,  Row, Col, message,Tooltip} from 'antd';
import {
  WeaPopoverHrm,
  WeaLeftRightLayout,
  WeaTab,
  WeaTop,
  WeaSearchGroup,
  WeaFormItem,
  WeaBrowser,
  WeaInput,
  WeaSelect,
  WeaRightMenu,
  WeaLocaleProvider
} from 'ecCom';
import {WeaTableNew} from 'comsMobx';
import LeftCom from './LeftCom';

import * as Util from '../../../util/Util';
const WeaTable = WeaTableNew.WeaTable;
const {confirm} = Modal;
const getLabel = WeaLocaleProvider.getLabel;
const toJS = mobx.toJS;
@inject ('planAuditListStore')
@observer
export default class PlanAuditList extends React.Component {
  constructor (props) {
    super (props);
    this.state = {
      showSearchAd: false,
      isrefesh: false,
      topTab: [],

      _height: Util.getCurrentHeight (),
      heightInit: false,
      searchItems: [],
      tableSelectedRowKeys: [],
      searchTitle: '',
      showLeft: false,
      includeSubOption:[
        {
          key:"3",
          showname:getLabel('508780','含子分部') 
        },
        {
          key:"1",
          showname:getLabel('18919','仅本分部') 
        },
        {
          key:"2",
          showname:getLabel('18920','仅子分部') 
        },
      ],
      includeDepOption:[

        {
          key:"3",
          showname:getLabel('508784','含子部门') 
        },
        {
          key:"1",
          showname:getLabel('18916','仅本部门') 
        },
        {
          key:"2",
          showname:getLabel('18917','仅子部门') 
        },
      ]
    };
    this.store = this.props.planAuditListStore;
    this.scrollHeight = {y:this.state._height-250};
    this.rowSelection = {selectedRowKeys: this.state.tableSelectedRowKeys,
                         onChange: this.onTableSelectChange};
    window.planAuditRefresh=()=>{
      this.store.tableStore.reloadCurrent()
    }
  }
  componentWillMount () {
    //一些初始化请求
    this.store.getOption();
    this.resetSearchAd ();
    this.getTableData ();
    if(typeof this.props.getNoAuditCount == 'function'){
      this.props.getNoAuditCount();
    }
    //设置windowkey
    Util.setWindowKeys("2",getLabel('505884','报告审批'));
  }

  //重置查询条件
  resetSearchAd () {
    let {planAuditListStore} = this.props;
    planAuditListStore.resetSearchConditions ();
  }
  //搜索
  advanceSearch () {
    let {planAuditListStore} = this.props;
    planAuditListStore.getAuditListTable ({refresh:1});
    this.setState({tableSelectedRowKeys: []});
    this.cancleSearchAd ();
  }

  auditOperationRequest = type => {
    let {planAuditListStore} = this.props;
    planAuditListStore.setData (type, 'operation');
    planAuditListStore.auditOperation (this.props.getNoAuditCount);

  };

  //确定批准此总结计划?

  auditOpreation = type => {
    let _this = this;
    const {tableSelectedRowKeys} = this.state;
    if (tableSelectedRowKeys.length < 1) {
      message.info (getLabel('508892','请选择至少一条数据进行操作') );
      return;
    }
    let title = type == 'quick_approve' ?getLabel('508893','确定批准此总结计划?')  : getLabel('508897','确定退回此总结计划?') ;
    confirm ({
      title: getLabel('508899','操作提示') ,
      content: title,
      okText: getLabel('826','确定') ,
      okType: 'danger',
      cancelText: getLabel('31129','取消') ,
      onOk () {
        _this.auditOperationRequest (type);
        _this.setState({tableSelectedRowKeys:[]})
      },
      onCancel () {},
    });
  };

  allAuditReuqest = type => {
    let _this = this;
    let title = type == 'all_approve'
      ? getLabel('508902','确定批准满足当前查询条件的全部总结计划?') 
      : getLabel('508903','确定退回满足当前查询条件的全部总结计划?') ;
    confirm ({
      title: getLabel('508899','操作提示') ,
      content: title,
      okText: getLabel('826','确定') ,
      okType: 'danger',
      cancelText: getLabel('31129','取消') ,
      onOk () {
        _this.auditOperationRequest (type);
      },
      onCancel () {},
    });
  };

  cancleSearchAd () {
    this.setState ({
      showSearchAd: false,
    });
  }
  getTabButtonsAd () {
    return [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@9pbqf0@search`} type="primary" onClick={() => this.advanceSearch ()}>{getLabel('388113','搜索') }</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@acnuws@reset`} type="ghost" onClick={() => this.resetSearchAd ()}>{getLabel('2022','重置') }</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@uzw2uk@cancel`} type="ghost" onClick={() => this.cancleSearchAd (false)}>
        {getLabel('31129','取消') }
      </Button>,
    ];
  }

  showCurrentChange = current => {};
  onShowSizeChange = (current, pageSize) => {};
  onTableSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState ({tableSelectedRowKeys: selectedRowKeys});
    this.onSearchAreaSelectChange (selectedRowKeys, 'planIds');
  };

  getParams = () => {
    let {planAuditListStore} = this.props;
    let params = planAuditListStore.data;

    return params;
  };

  getTableData () {
    const params = this.getParams ();
    let {planAuditListStore} = this.props;
    planAuditListStore.getAuditListTable (params);
  }

  getSearchsAd = () => {
    return (
      <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@4wb5ef`}
        title={getLabel('32905','常用条件')}
        items={this.getSearchItems ()}
        showGroup={true}
        col={2}
      />
    );
  };

  getSearchItems = () => {
    const {planAuditListStore: {data}} = this.props;
    const {dateTypeOptions} = this.store
    let items = [];

    items.push ({
      com: (
        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@wke88w@titlevalue`} label={getLabel('24986','标题') } ratio1to2>
          <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@erv05w@titlevalue`}
            value={data.searchTitleValue}
            onChange={e =>
              this.onSearchAreaSelectChange (e, 'searchTitleValue')}
            onPressEnter={()=>this.advanceSearch()}
          />
        </WeaFormItem>
      ),
    });
    items.push ({
      com: (
        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@pevdb2@datatype`} label={getLabel('15386','周期') } ratio1to2>
          <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@9kylmg@datatype`}
            hasBorder
            options={toJS(dateTypeOptions)}
            value={data.searchDateType}
            onChange={v => this.onSearchAreaSelectChange (v, 'searchDateType')}
          />
        </WeaFormItem>
      ),
    });

    items.push ({
      com: (
        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@zhf4gq@hrmname`} label={getLabel('30042','人员') } ratio1to2>
          <div className="hrm">

            <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@5ixg43@hrmname`}
              type={17}
              title={getLabel('179','人力资源') }
              style={{display: 'block'}}
              replaceDatas={this.store.hrmData}
              isSingle={false}
              value={data.searchHumSelectValue}
              onChange={(ids, names, datas) =>{
                this.onSearchAreaSelectChange (ids, 'searchHumSelectValue')
                this.onSearchAreaSelectChange (names, 'searchHumNameSelectValue')

                }
              }
                
            />
          </div>
        </WeaFormItem>
      ),
    });

    items.push ({
      com: (
        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@r7o81o@includesub`} label={getLabel('33553','分部') } ratio1to2>
          <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@9lgruf@includesub`}>
            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@kt4ken@includesub`} md={12}>
              <div className="left-col">
                <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@zcmw37@includesub`}
                  hasBorder
                  options={this.state.includeSubOption}
                  value={data.searchIncludeSubSelectValue}
                  onChange={v =>
                    this.onSearchAreaSelectChange (
                      v,
                      'searchIncludeSubSelectValue'
                    )}
                />
              </div>
            </Col>
            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@zkarc1@subvalue`} md={12}>
              <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@upyquo@subvalue`}
                title={getLabel('33553','分部') }
                type={194}
                isSingle={false}
                value={data.searchSubSelectValue}
                onChange={(ids, names, datas) =>
                  this.onSearchAreaSelectChange (ids, 'searchSubSelectValue')}
              />
            </Col>

          </Row>

        </WeaFormItem>
      ),
    });

    items.push ({
      com: (
        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@1iojd9@includedept`} label={getLabel('27511','部门') } ratio1to2>
          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@8sokad@includedept`} md={12}>
            <div className="left-col">
              <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@tiizkd@includedept`}
                hasBorder
                options={this.state.includeDepOption}
                value={data.searchIncludeDepSelectValue}
                onChange={v => {
                  this.onSearchAreaSelectChange (
                    v,
                    'searchIncludeDepSelectValue'
                  );
                }}
              />
            </div>
          </Col>

          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@65dsb8@deptvalue`} md={12}>
            <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@b3j7ej@deptvalue`}
              type={57}
              title={getLabel('27511','部门') }
              isSingle={false}
              value={data.searchDepSelectValue}
              onChange={(ids, names, datas) =>
                this.onSearchAreaSelectChange (ids, 'searchDepSelectValue')}
            />
          </Col>

        </WeaFormItem>
      ),
    });
    this.onSearchAreaSelectChange (items, 'searchConditionItems');
    return items;
  };

  onSearchAreaSelectChange (ids, paramName) {
    const {planAuditListStore} = this.props;
    planAuditListStore.setData (ids, paramName);
  }

  showColumn = () => {
    const {planAuditListStore: {tableStore}} = this.props;
    tableStore.setColSetVisible (true);
    tableStore.tableColSet (true);
  };

  //省略号点击事件
  onOperatesClick = (record, index, operate, flag) => {
    let title, operation;
    let _this = this;
    if (operate.index == 0) {
      title = getLabel('508908','确认批准此报告？') ;
      operation = 'approve';
    } else {
      title = getLabel('508912','确认退回此报告？')       ;
      operation = 'return';
    }
    confirm ({
      title: getLabel('508899','操作提示') ,
      content: title,
      okText: getLabel('826','确定') ,
      okType: 'danger',
      cancelText: getLabel('31129','取消') ,
      onOk () {
        _this.store.singleAuditOperation (record.id, operation,_this.props.getNoAuditCount);
        _this.setState({tableSelectedRowKeys:[]})
      },
      onCancel () {},
    });
  };

  onSubClick(id, name){
    this.store.setData (id, 'searchHumSelectValue');
    this.store.setData (name, 'searchHumNameSelectValue');
    this.store.getAuditListTable ();
  }

  
  render () {
    const {planAuditListStore} = this.props;
    const {tableStore, loading, data} = planAuditListStore;

    const {
      showSearchAd,
      _height,
      datalist,
      tableSelectedRowKeys,
      topTab,
    } = this.state;
    const buttonDisabled = tableSelectedRowKeys.length>0?false:true
    const topButton=[
      // <Button type='primary' onClick={() => this.advanceSearch()}>搜索</Button>,
      <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@7mod5u@quick_approve`} title={getLabel('508656', '批准已选')}><Button ecId={`${this && this.props && this.props.ecId || ''}_Button@b8ugwj@quick_approve`} type='primary' disabled={buttonDisabled} onClick={() => this.auditOpreation ('quick_approve')}>{getLabel('142', '批准')}</Button></Tooltip>,
      <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@aanu1g@quick_return`} title={getLabel('508657', '退回已选')}><Button ecId={`${this && this.props && this.props.ecId || ''}_Button@q5d8kn@quick_return`} type='primary' disabled={buttonDisabled} onClick={() => this.auditOpreation ('quick_return')}>{getLabel('236', '退回')}</Button></Tooltip>,
      // <Button type='primary' disabled={buttonDisabled} onClick={() => this.allAuditReuqest ('all_approve')}>批准全部</Button>,
      // <Button type='primary' disabled={buttonDisabled} onClick={() => this.allAuditReuqest ('all_return')}>退回全部</Button>,
    ]

    const rightMenu = [
      {
        key: '0',
        icon: <i className="icon-coms-search" />,
        content: getLabel('388113','搜索') ,
        onClick: key => {
          this.advanceSearch ();
        },
      },
      {
        key: '1',
        icon: <i className="icon-coms-Approval" />,
        content:getLabel('142', '批准') ,
        disabled:buttonDisabled,
        onClick: key => {
          this.auditOpreation ('quick_approve');
        },
      },
      {
        key: '2',
        icon: <i className="icon-coms-go-back" />,
        content: getLabel('236', '退回') ,
        disabled:buttonDisabled,
        onClick: key => {
          this.auditOpreation ('quick_return');
        },
      },
      // {
      //   key: '3',
      //   icon: <i className="icon-coms-top" />,
      //   content: getLabel('508658','批准全部') ,
      //   onClick: key => {
      //     this.allAuditReuqest ('all_approve');
      //   },
      // },
      // {
      //   key: '4',
      //   icon: <i className="icon-coms-Revocation" />,
      //   content: getLabel('508660','退回全部') ,
      //   onClick: key => {
      //     this.allAuditReuqest ('all_return');
      //   },
      // },
      {
        key: 'BTN_COLUMN',
        icon: <i className="icon-coms-Custom" />,
        content: getLabel('32535','显示列定制') ,
        onClick: this.showColumn,
      },
    ];

    const weaTopConfig = {
      title: getLabel('508923','报告待审批列表') ,
      icon: <i className="icon-coms-implement" />,
      iconBgcolor: 'rgb(150, 53, 138)',
      buttons:topButton,
      showDropIcon: true,
      dropMenuDatas: rightMenu,
    };

    const weaTabConfig = {
      datas: topTab,
      searchType: ['advanced', 'base'],
      showSearchAd: showSearchAd,
      hideSearchAd: () => this.cancleSearchAd (),
      setShowSearchAd: bool => {
        this.setState ({
          showSearchAd: bool,
        });
      },
      buttonsAd: this.getTabButtonsAd (),
      searchsAd: this.getSearchsAd (),
      searchsBaseValue: data.searchTitleValue,
      onSearch: () => {
        this.advanceSearch ();
      },
      onSearchChange: e => {
        planAuditListStore.setData (e, 'searchTitleValue');
        this.setState ({searchTitle: e});
      },
    };

    // const weaTableConfig = {
    //   comsWeaTableStore: tableStore, // table store
    //   hasOrder: true, // 是否启用排序
    //   needScroll: true, // 是否启用table内部列表滚动，将自适应到父级高度
    //   rowSelection: {
    //     selectedRowKeys: tableSelectedRowKeys,
    //     onChange: this.onTableSelectChange,
    //   },
    //   scroll: {y: window.innerHeight - 250},
    //   onOperatesClick: this.onOperatesClick,
    // };
    return (
      <div className="wea-workrelate-plan-auditlist" style={{height: "100vh"}}>

        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@utmcgd`} datas={rightMenu} showUrlItem={false} collectParams={{
                    favname: getLabel('505884','报告审批'),
                    favouritetype: 5,
                    link: '/spa/workrelate/static/index.html?#/main/workrelate/plan/planIndex?menutype=2',
                    importantlevel: 1,
                }}>
          <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@05l6qs`} {...weaTopConfig} />
          <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@e14mwt`}
            isNew={true}
            leftWidth={220}
            leftCom={<LeftCom ecId={`${this && this.props && this.props.ecId || ''}_LeftCom@w0j4jr`} />}
            showLeft={this.state.showLeft}
            onCollapse={showLeft => this.setState ({showLeft})}
          >
            <div style={{height: _height}}>
              <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@gdu1z3`} {...weaTabConfig} />
              <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@jr6ac9`} // table内部做了loading加载处理，页面就不需要再加了
                comsWeaTableStore={tableStore} // table store
                hasOrder={true} // 是否启用排序
                needScroll={true} // 是否启用table内部列表滚动，将自适应到父级高度
                rowSelection={this.rowSelection}
                scroll={this.scrollHeight}
                onOperatesClick={this.onOperatesClick}
              />
            </div>
          </WeaLeftRightLayout>
        </WeaRightMenu>
        <WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@vldrcr`} />

      </div>
    );
  }
}
